﻿using DeviceMaintainGIS.Entity;
using DeviceMaintainGIS.Model.DevInfo;
using DeviceMaintainGIS.Model.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;


namespace AchieveManageWeb.Controllers
{
    public class DevInfoController : Controller
    {
        //
        // GET: /DevInfo/

        public ActionResult Index()
        {
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linq = from d in Entities.DevInfo_Tab
                           group d by d.DeviceLevel into g
                           select new DevTabDeviceLevel
                           {
                               Level = g.Key
                           };
                ViewBag.DevTabDeviceLevelList = linq.OrderBy(i => i.Level).ToList();

            }
            return View();
        }

        public ActionResult DevAdd()
        {
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linq = from a in Entities.DevType_Tab
                           select new DevTypeModel
                           {
                               DeviceTypeId = a.DeviceTypeId,
                               DeviceName = a.DeviceName
                           };
                List<DevTypeModel> list = linq.ToList();
                ViewBag.DevTypeList = list;

                var linqs = from d in Entities.DevInfo_Tab
                            group d by d.DeviceLevel into g
                            select new DevTabDeviceLevel
                            {
                                Level = g.Key
                            };
                ViewBag.DevTabDeviceLevelList = linqs.OrderBy(i => i.Level).ToList();
            };

            return View();
        }

        /// <summary>
        /// 设备编辑初始化
        /// </summary>
        /// <returns></returns>
        public ActionResult DevEdit()
        {
            DevInfoModel DevModel = new DevInfoModel();
            int DevID = Request["ID"] == null ? 1 : int.Parse(Request["ID"].ToString());

            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linq = from a in Entities.DevType_Tab
                           select new DevTypeModel
                           {
                               DeviceTypeId = a.DeviceTypeId,
                               DeviceName = a.DeviceName
                           };
                List<DevTypeModel> list = linq.ToList();
                ViewBag.DevTypeList = list;
                var linqDeviceLevel = from d in Entities.DevInfo_Tab
                                      group d by d.DeviceLevel into g
                                      select new DevTabDeviceLevel
                                      {
                                          Level = g.Key
                                      };
                ViewBag.DevTabDeviceLevelList = linqDeviceLevel.OrderBy(i => i.Level).ToList();

                //获取设备的父ID
                DevTpRelation_Tab ParentDevTpRelation = Entities.DevTpRelation_Tab.Where(i => i.DeviceId == DevID).FirstOrDefault();



                var linqs = from a in Entities.DevInfo_Tab.Where(i => i.ID == DevID)
                            select new DevInfoModel
                            {
                                ID = a.ID,
                                DeviceId = a.DeviceId,
                                DeviceName = a.DeviceName,
                                DeviceLevel = a.DeviceLevel,
                                DeviceTypeId = a.DeviceTypeId,
                                FactorySerial = a.FactorySerial,
                                CompanySerial = a.CompanySerial,
                                FModelSize = a.FModelSize,
                                CModelSize = a.CModelSize,
                                Purchaser = a.Purchaser,
                                PurchaseTime = a.PurchaseTime,
                                WarrantyTime = a.WarrantyTime,
                                DeviceFactory = a.DeviceFactory,
                                DeviceTel = a.DeviceTel,
                                RepairFactory = a.RepairFactory,
                                RepairTel = a.RepairTel,
                                Software = a.Software,
                                SoftwareVersion = a.SoftwareVersion,
                                State = a.State,
                                RepairFactoryManager = a.RepairFactoryManager
                            };
                ViewBag.DevTypeList = list;
                DevModel = linqs.FirstOrDefault();
                if (ParentDevTpRelation != null)
                {
                    DevInfo_Tab ParentDev = Entities.DevInfo_Tab.Where(i => i.ID == ParentDevTpRelation.Parent).FirstOrDefault();
                    ViewBag.ParentID = ParentDevTpRelation.Parent;
                    //a.DeviceName + "(" + a.CompanySerial + ")",
                    ViewBag.DeviceName = ParentDev.DeviceName + "(" + ParentDev.CompanySerial + ")";
                    //ViewBag.ParentID = ParentDevTpRelation.Parent;
                }
                else
                {
                    ViewBag.ParentID = -1;
                }
            };

            return View(DevModel);
        }
        /// <summary>
        /// 设备编辑
        /// </summary>
        /// <param name="dim"></param>
        /// <returns></returns>
        public ActionResult DevInfoEdit(DevInfoModel dim)
        {
            int code = 0;
            //设备原有等级
            int intOleDeviceLevel = 0;
            //设备新等级
            int intNewDeviceLevel = 0;
            //新关系路径
            string strNewPath = "";

            //新关系路径
            string strOlePath = "";
            using (CYOADBEntities Entities = new CYOADBEntities())
            {


                DevInfo_Tab newParentDevModel = new DevInfo_Tab();
                //父级设备的关系
                DevTpRelation_Tab newParentDevTpRelation = new DevTpRelation_Tab();

                //获取设备信息
                DevInfo_Tab DevModel = Entities.DevInfo_Tab.Where(i => i.ID == dim.ID).FirstOrDefault();
                //获取设备的关系
                DevTpRelation_Tab DevTpRelation = Entities.DevTpRelation_Tab.Where(i => i.DeviceId == dim.ID).FirstOrDefault();

                if (DevModel == null)
                {
                    return Content("{\"msg\":\"修改失败！未查询到此设备\",\"success\":false}");
                }
                int tmpDeviceIdCount = Entities.DevInfo_Tab.Where(i => i.DeviceId == dim.DeviceId).Count();
                if (tmpDeviceIdCount > 1)
                {
                    return Content("{\"msg\":\"添加失败！设备编号已存在！\",\"success\":false}");
                }
                int tmpDeviceNameCount = Entities.DevInfo_Tab.Where(i => i.CompanySerial == dim.CompanySerial).Count();
                if (tmpDeviceNameCount > 1)
                {
                    return Content("{\"msg\":\"添加失败！公司序列号已存在！\",\"success\":false}");
                }
                //int tmpDeviceCompanySerial = Entities.DevInfo_Tab.Where(i => i.CompanySerial == dim.CompanySerial).Count();
                //if (tmpDeviceNameCount > 1)
                //{
                //    return Content("{\"msg\":\"添加失败！设备公司序列号重复！\",\"success\":false}");
                //}
                intOleDeviceLevel = DevModel.DeviceLevel;
                //DevModel.DeviceId = dim.DeviceId;
                DevModel.DeviceName = dim.DeviceName;
                //if(dim.DeviceTypeId!=null)
                //{ 
                DevModel.DeviceTypeId = dim.DeviceTypeId;
                //}

                DevModel.FactorySerial = dim.FactorySerial;
                DevModel.CompanySerial = dim.CompanySerial;
                DevModel.FModelSize = dim.FModelSize;
                DevModel.CModelSize = dim.CModelSize;
                DevModel.Software = dim.Software;
                DevModel.SoftwareVersion = dim.SoftwareVersion;
                DevModel.Purchaser = dim.Purchaser;
                DevModel.PurchaseTime = dim.PurchaseTime;
                DevModel.WarrantyTime = dim.WarrantyTime;
                DevModel.DeviceFactory = dim.DeviceFactory;
                DevModel.DeviceTel = dim.DeviceTel;
                DevModel.RepairFactory = dim.RepairFactory;
                DevModel.RepairTel = dim.RepairTel;
                DevModel.RepairFactoryManager = dim.RepairFactoryManager;

                if (DevTpRelation != null && dim.ParentDevID != DevTpRelation.Parent)
                {
                    //获取新父级设备信息
                    newParentDevModel = Entities.DevInfo_Tab.Where(i => i.ID == dim.ParentDevID).FirstOrDefault();
                    //获取新父级设备关系
                    newParentDevTpRelation = Entities.DevTpRelation_Tab.Where(i => i.DeviceId == dim.ParentDevID).FirstOrDefault();

                    if (newParentDevModel == null)
                    {
                        return Content("{\"msg\":\"添加失败！上级设备不存在！\",\"success\":false}");
                    }
                    if (newParentDevModel.State == 2)
                    {
                        return Content("{\"msg\":\"添加失败！主设备是报废设备，无法添加子设备！\",\"success\":false}");
                    }
                    //子设备状态和主设备状态一致
                    DevModel.State = newParentDevModel.State;
                    //设置设备的新等级信息
                    intNewDeviceLevel = newParentDevModel.DeviceLevel + 1;
                    DevModel.DeviceLevel = intNewDeviceLevel;
                }




                Entities.DevInfo_Tab.Add(DevModel);
                Entities.Entry<DevInfo_Tab>(DevModel).State = System.Data.Entity.EntityState.Modified;
                code = Entities.SaveChanges();

                if (code > 0)
                {
                    //如果当前设备关系为空 添加关系
                    if (DevTpRelation == null)
                    {
                        //当前设备赋值关系
                        DevTpRelation_Tab newDevTpRelationTab = new DevTpRelation_Tab();
                        string newID = Guid.NewGuid().ToString();
                        newDevTpRelationTab.RelationId = newID;
                        newDevTpRelationTab.Parent = newParentDevModel.ID;
                        newDevTpRelationTab.DeviceId = DevModel.ID;

                        //判断父级设备关系是否为空
                        if (newParentDevTpRelation != null)
                        {
                            strNewPath = newParentDevTpRelation.Path + DevModel.ID + ",";
                            newDevTpRelationTab.Path = strNewPath;
                        }
                        else
                        {
                            strNewPath = newParentDevModel.ID + "," + DevModel.ID + ",";
                            newDevTpRelationTab.Path = strNewPath;
                        }

                        Entities.DevTpRelation_Tab.Add(newDevTpRelationTab);
                        Entities.Entry<DevTpRelation_Tab>(newDevTpRelationTab).State = System.Data.Entity.EntityState.Added;
                        Entities.SaveChanges();
                    }
                    else
                    {
                        strOlePath = DevTpRelation.Path;
                        DevTpRelation.Parent = newParentDevModel.ID;
                        //判断父级设备关系是否为空
                        if (newParentDevTpRelation != null)
                        {
                            strNewPath = newParentDevTpRelation.Path + DevModel.ID + ",";
                            DevTpRelation.Path = strNewPath;
                        }
                        else
                        {
                            strNewPath = newParentDevModel.ID + "," + DevModel.ID + ",";
                            DevTpRelation.Path = strNewPath;
                        }
                        Entities.DevTpRelation_Tab.Add(DevTpRelation);
                        Entities.Entry<DevTpRelation_Tab>(DevTpRelation).State = System.Data.Entity.EntityState.Modified;
                        Entities.SaveChanges();

                        //获取当前设备下的所有子设备
                        List<DevTpRelation_Tab> DevTpRelationTabList = Entities.DevTpRelation_Tab.Where(i => i.Path.StartsWith(strOlePath) && i.DeviceId != DevModel.ID).ToList();
                        //判断子设备是否为空
                        if (DevTpRelationTabList.Count > 0)
                        {
                            foreach (DevTpRelation_Tab dtrt in DevTpRelationTabList)
                            {
                                string tmpPath = dtrt.Path.Replace(strOlePath, strNewPath);
                                dtrt.Path = tmpPath;

                                DevInfo_Tab sonDevModel = Entities.DevInfo_Tab.Where(i => i.ID == dtrt.DeviceId).FirstOrDefault();
                                sonDevModel.DeviceLevel = sonDevModel.DeviceLevel + intNewDeviceLevel - intOleDeviceLevel;

                                Entities.DevTpRelation_Tab.Add(dtrt);
                                Entities.Entry<DevTpRelation_Tab>(dtrt).State = System.Data.Entity.EntityState.Modified;


                                Entities.DevInfo_Tab.Add(sonDevModel);
                                Entities.Entry<DevInfo_Tab>(sonDevModel).State = System.Data.Entity.EntityState.Modified;
                                Entities.SaveChanges();

                            }
                        }
                    }
                    return Content("{\"msg\":\"修改成功！\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"修改失败！入库失败\",\"success\":false}");
                }
            }
        }

        /// <summary>
        /// 删除设备
        /// </summary>
        /// <param name="dim"></param>
        /// <returns></returns>
        public ActionResult DevInfoDel(DevInfoModel dim)
        {
            int DevID = Request["ID"] == null ? 1 : int.Parse(Request["ID"].ToString());
            int Code = 0;
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                //获取设备信息
                DevInfo_Tab DevModel = Entities.DevInfo_Tab.Where(i => i.ID == DevID).FirstOrDefault();
                //获取设备的关系
                DevTpRelation_Tab DevTpRelation = Entities.DevTpRelation_Tab.Where(i => i.DeviceId == DevID).FirstOrDefault();
                if (DevModel.State != 0)
                {
                    return Content("{\"msg\":\"删除失败！设备已出库或已报废！\",\"success\":false}");
                }

                Entities.DevInfo_Tab.Add(DevModel);
                Entities.Entry<DevInfo_Tab>(DevModel).State = System.Data.Entity.EntityState.Deleted;

                //获取设备出库信息
                DevProRelation_Tab DevProRelationTab = Entities.DevProRelation_Tab.Where(i => i.DeviceId == DevModel.DeviceId).FirstOrDefault();

                if (DevProRelationTab != null)
                {
                    Entities.DevProRelation_Tab.Add(DevProRelationTab);
                    Entities.Entry<DevProRelation_Tab>(DevProRelationTab).State = System.Data.Entity.EntityState.Deleted;
                }

                string DevPath = "";
                if (DevTpRelation != null)
                {
                    Entities.DevTpRelation_Tab.Add(DevTpRelation);
                    Entities.Entry<DevTpRelation_Tab>(DevTpRelation).State = System.Data.Entity.EntityState.Deleted;
                    DevPath = DevTpRelation.Path;
                }
                else
                {
                    DevPath = DevModel.ID + ",";
                }

                //获取当前设备下的所有子设备
                List<DevTpRelation_Tab> DevTpRelationTabList = Entities.DevTpRelation_Tab.Where(i => i.Path.StartsWith(DevPath) && i.DeviceId != DevModel.ID).ToList();

                if (DevTpRelationTabList.Count > 0)
                {
                    foreach (DevTpRelation_Tab dtrt in DevTpRelationTabList)
                    {
                        DevInfo_Tab sonDevModel = Entities.DevInfo_Tab.Where(i => i.ID == dtrt.DeviceId).FirstOrDefault();
                        Entities.DevInfo_Tab.Add(sonDevModel);
                        Entities.Entry<DevInfo_Tab>(sonDevModel).State = System.Data.Entity.EntityState.Deleted;
                        Entities.DevTpRelation_Tab.Add(dtrt);
                        Entities.Entry<DevTpRelation_Tab>(dtrt).State = System.Data.Entity.EntityState.Deleted;
                        if (sonDevModel.State != 0)
                        {
                            return Content("{\"msg\":\"删除失败！子设备已出库或已报废！\",\"success\":false}");
                        }
                    }
                }

                Code = Entities.SaveChanges();
                if (Code > 0)
                {
                    new DocumentController().DelDocumentByID(DevModel.DeviceId);
                    return Content("{\"msg\":\"删除成功！\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"删除失败！\",\"success\":false}");
                }
                //if (Code >0)
                //{
                //    string DevPath = "";
                //    if (DevTpRelation != null)
                //    {
                //        Entities.DevTpRelation_Tab.Add(DevTpRelation);
                //        Entities.Entry<DevTpRelation_Tab>(DevTpRelation).State = System.Data.Entity.EntityState.Deleted;
                //        DevPath = DevTpRelation.Path;
                //    }
                //    else
                //    {
                //        DevPath = DevModel.ID + ",";
                //    }

                //    //获取当前设备下的所有子设备
                //    List<DevTpRelation_Tab> DevTpRelationTabList = Entities.DevTpRelation_Tab.Where(i => i.Path.StartsWith(DevPath) && i.DeviceId != DevModel.ID).ToList();

                //    if (DevTpRelationTabList.Count > 0)
                //    {
                //        //循环取删除设备的子设备
                //        foreach (DevTpRelation_Tab dtrt in DevTpRelationTabList)
                //        {
                //            DevInfo_Tab sonDevModel = Entities.DevInfo_Tab.Where(i => i.ID == dtrt.DeviceId).FirstOrDefault();
                //            sonDevModel.DeviceLevel = sonDevModel.DeviceLevel - DevModel.DeviceLevel;

                //            Entities.DevTpRelation_Tab.Add(dtrt);
                //            Entities.Entry<DevTpRelation_Tab>(dtrt).State = System.Data.Entity.EntityState.Modified;
                //            if (dtrt.Parent == DevModel.ID)
                //            {
                //                Entities.DevTpRelation_Tab.Add(dtrt);
                //                Entities.Entry<DevTpRelation_Tab>(dtrt).State = System.Data.Entity.EntityState.Deleted;
                //            }
                //            else
                //            {
                //                string tmpPath = dtrt.Path.Replace(DevPath, "");
                //                dtrt.Path = tmpPath;
                //                Entities.DevTpRelation_Tab.Add(dtrt);
                //                Entities.Entry<DevTpRelation_Tab>(dtrt).State = System.Data.Entity.EntityState.Modified;
                //            }
                //        }
                //        Entities.SaveChanges();
                //    }

            }
        }
        /// <summary>
        /// 获取父设备信息用于下拉列表
        /// </summary>
        /// <returns></returns>
        public string GetSelDevInfo(int DeviceLevel = 0)
        {
            string strJson = "";
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linq = from a in Entities.DevInfo_Tab.Where(i => i.State == 0 && i.DeviceLevel == DeviceLevel)
                           select new SelDevInfoModel
                           {
                               id = a.ID,
                               text = a.DeviceName + "(" + a.CompanySerial + ")",

                           };
                List<SelDevInfoModel> SelDevInfoModelList = linq.ToList();
                JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
                strJson = jsonSerialize.Serialize(SelDevInfoModelList);
            }
            return strJson;
        }
        /// <summary>
        /// 添加设备信息
        /// </summary>
        /// <param name="dim"></param>
        /// <returns></returns>
        public ActionResult DevInfoAdd(DevInfoModel dim)
        {
            DevInfo_Tab FatherDevModel = new DevInfo_Tab();
            DevInfo_Tab dit = new DevInfo_Tab();
            dit.DeviceId = Guid.NewGuid().ToString();//dim.DeviceId;
            dit.DeviceName = dim.DeviceName;
            dit.DeviceTypeId = dim.DeviceTypeId;

            dit.FactorySerial = dim.FactorySerial;
            dit.CompanySerial = dim.CompanySerial;
            dit.FModelSize = dim.FModelSize;
            dit.CModelSize = dim.CModelSize;
            dit.Software = dim.Software;
            dit.SoftwareVersion = dim.SoftwareVersion;
            dit.Purchaser = dim.Purchaser;
            dit.PurchaseTime = dim.PurchaseTime;
            dit.WarrantyTime = dim.WarrantyTime;
            dit.DeviceFactory = dim.DeviceFactory;
            dit.DeviceTel = dim.DeviceTel;
            dit.RepairFactory = dim.RepairFactory;
            dit.RepairTel = dim.RepairTel;
            dit.AddTime = System.DateTime.Now;
            dit.RepairFactoryManager = dim.RepairFactoryManager;
            dit.State = 0;
            int code = 0;
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                //查询输入的设备号是否已存在
                int tmpDeviceIdCount = Entities.DevInfo_Tab.Where(i => i.DeviceId == dim.DeviceId).Count();
                if (tmpDeviceIdCount > 0)
                {
                    return Content("{\"msg\":\"添加失败！设备编号已存在！\",\"success\":false}");
                }
                //int tmpDeviceNameCount = Entities.DevInfo_Tab.Where(i => i.DeviceName == dim.DeviceName).Count();
                //if (tmpDeviceNameCount > 1)
                //{
                //    return Content("{\"msg\":\"添加失败！设备名称已存在！\",\"success\":false}");
                //}

                int tmpDeviceCompanySerial = Entities.DevInfo_Tab.Where(i => i.CompanySerial == dim.CompanySerial).Count();
                if (tmpDeviceCompanySerial > 0)
                {
                    return Content("{\"msg\":\"添加失败！设备公司序列号重复！\",\"success\":false}");
                }

                //判断是否选择了父级设备
                if (dim.ParentDevID != 0)
                {
                    //查询输入的设备号是否已存在
                    FatherDevModel = Entities.DevInfo_Tab.Where(i => i.ID == dim.ParentDevID).FirstOrDefault();
                    if (FatherDevModel != null)
                    {
                        if (FatherDevModel.State == 2)
                        {
                            return Content("{\"msg\":\"添加失败！主设备是报废设备，无法添加子设备！\",\"success\":false}");
                        }
                        dit.DeviceLevel = FatherDevModel.DeviceLevel + 1;
                        dit.State = FatherDevModel.State;
                    }
                    else
                    {
                        dit.DeviceLevel = 1;
                    }
                }
                else
                {
                    dit.DeviceLevel = 1;
                }
                Entities.DevInfo_Tab.Add(dit);
                Entities.Entry<DevInfo_Tab>(dit).State = System.Data.Entity.EntityState.Added;
                code = Entities.SaveChanges();
            };
            if (code > 0)
            {
                //判断是否选择了父级设备
                if (dim.ParentDevID != 0 && FatherDevModel != null)
                {
                    using (CYOADBEntities Entities = new CYOADBEntities())
                    {
                        //获取父级设备的设备关系数据
                        DevTpRelation_Tab ParentDevTpRelation = Entities.DevTpRelation_Tab.Where(i => i.DeviceId == FatherDevModel.ID).FirstOrDefault();
                        //当前设备赋值关系
                        DevTpRelation_Tab newDevTpRelationTab = new DevTpRelation_Tab();
                        string newID = Guid.NewGuid().ToString();
                        newDevTpRelationTab.RelationId = newID;
                        newDevTpRelationTab.Parent = FatherDevModel.ID;
                        newDevTpRelationTab.DeviceId = dit.ID;

                        //判断父级设备关系是否为空
                        if (ParentDevTpRelation != null)
                        {
                            newDevTpRelationTab.Path = ParentDevTpRelation.Path + dit.ID + ",";
                        }
                        else
                        {
                            newDevTpRelationTab.Path = FatherDevModel.ID + "," + dit.ID + ",";
                        }
                        Entities.DevTpRelation_Tab.Add(newDevTpRelationTab);
                        Entities.Entry<DevTpRelation_Tab>(newDevTpRelationTab).State = System.Data.Entity.EntityState.Added;
                        Entities.SaveChanges();
                    };
                }
                return Content("{\"msg\":\"添加成功！\",\"success\":true}");
            }
            else
            {
                return Content("{\"msg\":\"添加失败！入库失败\",\"success\":false}");
            }

        }


        /// <summary>
        /// 根据条件获取设备列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAllDevInfo()
        {
            try
            {
                //首先获取前台传递过来的参数
                int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);
                int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);

                string selDeviceName = Request["selDeviceName"] == null ? "" : Request["selDeviceName"].ToString();
                string selCompanySerial = Request["selCompanySerial"] == null ? "" : Request["selCompanySerial"].ToString();
                string selCModelSize = Request["selCModelSize"] == null ? "" : Request["selCModelSize"].ToString();
                int selDeviceLevel = Request["selDeviceLevel"] == null || Request["selDeviceLevel"].ToString() == "" ? 1 : int.Parse(Request["selDeviceLevel"].ToString());
                int selDevState = Request["selDevState"] == null || Request["selDevState"].ToString() == "" ? 0 : int.Parse(Request["selDevState"].ToString());
                DateTime tmp = DateTime.ParseExact("19000101", "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
                DateTime selStartWarrantyTime = Request["selStartWarrantyTime"] == null || Request["selStartWarrantyTime"].ToString() == "" ? tmp : DateTime.Parse(Request["selStartWarrantyTime"].ToString());
                DateTime selEndWarrantyTime = Request["selEndWarrantyTime"] == null || Request["selEndWarrantyTime"].ToString() == "" ? tmp : DateTime.Parse(Request["selEndWarrantyTime"].ToString());

                string strJson;
                int totalCount;   //输出参数
                using (CYOADBEntities Entities = new CYOADBEntities())
                {


                    var linq = from a in Entities.DevInfo_Tab
                               join f in Entities.DevType_Tab on a.DeviceTypeId equals f.DeviceTypeId
                                into tmpLocaType
                               let k = tmpLocaType.FirstOrDefault()
                               select new DevInfoModel
                               {
                                   ID = a.ID,
                                   DeviceId = a.DeviceId,
                                   DeviceName = a.DeviceName,
                                   DeviceTypeId = a.DeviceTypeId,
                                   DeviceTypeName = k == null ? "" : k.DeviceName,
                                   FactorySerial = a.FactorySerial,
                                   CompanySerial = a.CompanySerial,
                                   FModelSize = a.FModelSize,
                                   CModelSize = a.CModelSize,
                                   Purchaser = a.Purchaser,
                                   PurchaseTime = a.PurchaseTime,
                                   WarrantyTime = a.WarrantyTime,
                                   DeviceFactory = a.DeviceFactory,
                                   DeviceTel = a.DeviceTel,
                                   DeviceLevel = a.DeviceLevel,
                                   State = a.State
                               };
                    //设备名称
                    if (!string.IsNullOrEmpty(selDeviceName))
                    {
                        linq = linq.Where(i => i.DeviceName.Contains(selDeviceName));
                    }
                    //公司序列号
                    if (!string.IsNullOrEmpty(selCompanySerial))
                    {
                        linq = linq.Where(i => i.CompanySerial.Contains(selCompanySerial));
                    }
                    //公司规格型号
                    if (!string.IsNullOrEmpty(selCModelSize))
                    {
                        linq = linq.Where(i => i.CModelSize.Contains(selCModelSize));
                    }
                    //设备状态

                    linq = linq.Where(i => i.State == selDevState);
                    //设备等级
                    linq = linq.Where(i => i.DeviceLevel == selDeviceLevel);
                    //质保期
                    if (selStartWarrantyTime != tmp && selEndWarrantyTime != tmp)
                    {
                        linq = linq.Where(a => a.WarrantyTime >= selStartWarrantyTime && a.WarrantyTime <= selEndWarrantyTime);
                    }
                    totalCount = linq.Count();
                    List<DevInfoModel> list = linq.OrderBy(i => i.ID).Take(pagesize * pageindex).Skip(pagesize * (pageindex - 1)).ToList();

                    JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
                    strJson = jsonSerialize.Serialize(list);

                };

                var jsonResult = new { total = totalCount.ToString(), rows = strJson };
                return Content("{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}");
            }
            catch (Exception ee)
            {
                return Content("{\"total\": 0,\"rows\":''}");
            }
        }



        public ActionResult GetDevInfoByDeviceGuid()
        {
            int ParenDevID = Request["ID"] == null ? 1 : int.Parse(Request["ID"].ToString());
            //首先获取前台传递过来的参数
            int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);
            int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);

            string strJson;
            int totalCount;   //输出参数
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                //获得点选的设备信息
                DevInfo_Tab ParentDevModel = Entities.DevInfo_Tab.Where(i => i.ID == ParenDevID).FirstOrDefault();
                //获得点选设备关系信息
                DevTpRelation_Tab ParentDevTpRelation = Entities.DevTpRelation_Tab.Where(i => i.DeviceId == ParenDevID).FirstOrDefault();

                //获取子设备的路径
                string strPath = "";
                if (ParentDevTpRelation == null)
                {
                    strPath = ParentDevModel.ID + ",";
                }
                else
                {
                    strPath = ParentDevTpRelation.Path;
                }



                var linq = from b in Entities.DevTpRelation_Tab.Where(i => i.Path.Contains(strPath))// && i.DeviceId != ParenDevID)
                           join f in Entities.DevInfo_Tab on b.DeviceId equals f.ID
                            into tmpDevInfoTab
                           from a in tmpDevInfoTab.DefaultIfEmpty()
                               //let a = tmpDevInfoTab.FirstOrDefault()
                           join f in Entities.DevType_Tab on a.DeviceTypeId equals f.DeviceTypeId
                            into tmpDevType
                           let k = tmpDevType.FirstOrDefault()

                           select new DevInfoModel
                           {
                               ID = a == null ? 0 : a.ID,
                               DeviceId = a == null ? "" : a.DeviceId,
                               DeviceName = a == null ? "" : a.DeviceName,
                               DeviceTypeId = a == null ? "" : a.DeviceTypeId,
                               DeviceTypeName = k == null ? "" : k.DeviceName,
                               FactorySerial = a == null ? "" : a.FactorySerial,
                               CompanySerial = a == null ? "" : a.CompanySerial,
                               FModelSize = a == null ? "" : a.FModelSize,
                               CModelSize = a == null ? "" : a.CModelSize,
                               Purchaser = a == null ? "" : a.Purchaser,
                               PurchaseTime = a == null ? System.DateTime.Now : a.PurchaseTime,
                               WarrantyTime = a == null ? System.DateTime.Now : a.WarrantyTime,
                               DeviceFactory = a == null ? "" : a.DeviceFactory,
                               DeviceTel = a == null ? "" : a.DeviceTel,
                               State = a == null ? 0 : a.State,
                               DeviceLevel = a == null ? -1 : a.DeviceLevel,
                           };
                linq = linq.Where(i => i.DeviceLevel == (ParentDevModel.DeviceLevel + 1));
                totalCount = linq.Count();
                List<DevInfoModel> list = linq.OrderBy(i => i.ID).Take(pagesize * pageindex).Skip(pagesize * (pageindex - 1)).ToList();

                JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
                strJson = jsonSerialize.Serialize(list);


                var jsonResult = new { total = totalCount.ToString(), rows = strJson };
                return Content("{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}");

            };
        }
    }
}
